package controllers

import (
	"encoding/json"
	"new/dao"
	"new/kpg/app"
	"new/kpg/e"
	"new/models"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)

	username := m["username"]
	password := m["password"]
	users, _, err := dao.GetAllUser()
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	for _, user := range users {
		if user.Name == username && user.Password == password {
			app.OK(c, map[string]interface{}{}, "登录成功")
			return
		}
	}
	app.INFO(c, 30000, "用户名或密码错误")
}

func Register(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)

	UserName := m["username"]
	Password := m["password"]

	_, total, _ := dao.GetAllUser()

	err := dao.AddUser(models.User{ID: total + 1, Name: UserName, Password: Password})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "注册成功")
}
